import jwt
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView

# 装饰器的使用
from myapp.models import User
from myapp.myser import UserSer


# Create your views here.


def my_decorator(func):
    def warpper(request, *args, **kwargs):
        # 判断JWT逻辑
        uid = request.GET.get("uid")
        client_jwt = request.GET.get("jwt1", 'null')
        # 查询用户库中存储的上传的视频
        user = User.objects.filter(id=int(uid)).first()
        try:
            decode_jwt = jwt.decode(client_jwt, '0722', algorithms=['HS256'])
            # 进行jwt解密，如果jwt中存的视频与用户库中存储的不一致，说明播放视频并非用户上传视频
            if str(decode_jwt['img']) != user.img:
                return HttpResponse("非法视频")
        except Exception as e:
            return HttpResponse("非法视频！")

        return func(request, *args, **kwargs)

    return warpper


# 类装饰器调用
from django.utils.decorators import method_decorator

# 定义七牛云存储接口
from qiniu import Auth


class Qiniu_kaos(APIView):

    def get(self, request):
        # 定义密钥
        q = Auth('8UGGitAEzQ37UEPra3Vt1K49_x52yXiucp9PjqNr', 'UPuCeNYmUrcmnF9E_9PT9DVaklVY_llzBpgx63gy')
        # 指定上传空间mdmd2020
        token = q.upload_token('mdmd2020')
        print(token)
        res = {}
        res['token'] = token
        # 只给前端返回一个token
        return Response(res)


# 更新用户数据
class UpdateUser(APIView):
    def get(self, request):
        img = request.GET.get("img")
        uid = request.GET.get("uid")
        # 查询数据
        user = User.objects.get(id=int(uid))
        # 更新时将用户上传的视频进行JWT加密
        encode_jwt = jwt.encode({'img': str(img)}, '0722', algorithm='HS256')
        encode_str = str(encode_jwt, 'utf-8')

        user.img = img
        user.save()

        return Response({'code': 200, 'message': '更新成功', 'jwt': encode_str})


# 用户信息类
class UserInfo1(APIView):
    @method_decorator(my_decorator)
    def get(self, request):
        uid = request.GET.get('uid')
        user = User.objects.get(id=int(uid))
        user_ser = UserSer(user).data
        print(user_ser)
        return Response(user_ser)
